#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "NativeCameraController.h"
#import "SMLiveDetectionViewController.h"
#import <ContactsUI/ContactsUI.h>
#import "ToolsAuthorization.h"

typedef void (^FlutterResult)(id _Nullable  result);
@interface AppDelegate()<CNContactPickerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) FlutterViewController* controller;
@property (nonatomic, copy) FlutterResult callback;


@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GeneratedPluginRegistrant registerWithRegistry:self];
    
    self.controller = (FlutterViewController*)self.window.rootViewController;
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.controller];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = self.navigationController;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.window makeKeyAndVisible];
    [self registerMethodChannel];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}


-(void) registerMethodChannel{
    FlutterMethodChannel*  methodChannel = [FlutterMethodChannel
                                            methodChannelWithName:@"open_native_camera"
                                            binaryMessenger:(NSObject<FlutterBinaryMessenger> *) self.controller];
    [methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        
        //打开相机
        if ([call.method isEqualToString:@"open_camera"]) {
            NativeCameraController *cameraController = [NativeCameraController
                                                        doOpenCameraDetectionWithAction:^(id  _Nonnull response) {
                if(response){
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setObject:response forKey:@"image"];
                    result(dic);
                }
            }];
            [self.navigationController pushViewController:cameraController animated:true];
        }
        //打开人脸识别
        if([call.method isEqualToString:@"open_face"]){
            SMLiveDetectionViewController *controller = [SMLiveDetectionViewController doFaceDetectionWithActionList:@[] timeOut:30 callback:^(BOOL succed, NSDictionary * _Nonnull actionStatus, NSArray * _Nonnull faces) {
                NSLog(@"%@",(succed)?@"识别成功":@"识别失败");
                if(succed){
                    result(actionStatus);
                }
            }];
            [self.navigationController pushViewController:controller animated:true];
        }
        //打开通讯录
        if([call.method isEqualToString:@"open_contact"]){
            CNContactPickerViewController*vc = [CNContactPickerViewController new ];
            vc.delegate = self;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            self.callback = result;
            [self.controller presentViewController:vc animated:YES completion:nil];
        }
        //打开相册
        if([call.method isEqualToString:@"open_album"]){
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.delegate = self;
                controller.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
                controller.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
                self.callback = result;
                [self.controller  presentViewController:controller animated:YES completion:nil];
            }
        }
        //获取通讯录信息
        if([call.method isEqualToString:@"open_contact_address"]){
            [[ToolsAuthorization  sharedToolsInstance]getContact:^(id  _Nullable response) {
                result(response);
            }];
        }
        //获取安装app信息
        if([call.method isEqualToString:@"open_appInfo"]){
            [[ToolsAuthorization  sharedToolsInstance]getAppInfoList:^(id  _Nullable response) {
                result(response);
            }];
        }
        //获取手机设备信息
        if([call.method isEqualToString:@"open_deviceInfo"]){
            [[ToolsAuthorization  sharedToolsInstance]getDeviceInfo:^(id  _Nullable response) {
                result(response);
            }];
        }
    }];
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *faceImgStr = [self image2DataURL:image];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:faceImgStr forKey:@"image"];
    self.callback(dic);
}

- (NSString *) image2DataURL: (UIImage *) image
{
    NSString *mimeType  = @"image/png";
    NSData *data = UIImageJPEGRepresentation(image, 1);
    if(data.length >= 512 * 1024){
        CGFloat rate = 100.0 * 1024.0/data.length;
        data = UIImageJPEGRepresentation(image, rate);
    }
    NSData *_data =[data base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
            [data base64EncodedStringWithOptions: 0]];
}
-(NSDictionary*)contactsConversion:(NSDictionary*)dict{
    NSString *name = dict[@"givenName"];
    NSString *firstName =  dict[@"familyName"];
    NSDictionary *phoneNumbers = dict[@"phoneNumbers"][0];
    return @{
        @"name":[name isEqualToString:@""]?firstName:name ,
        @"phone":phoneNumbers[@"number"],
    };
}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    
    NSString *givenName = contact.givenName;
    NSString *familyName = contact.familyName;
    NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
    NSArray * phoneNumbers = contact.phoneNumbers;
    NSString *phoneStr = @"";
    NSString *label  = @"";
    for (CNLabeledValue<CNPhoneNumber*>*phone in phoneNumbers) {
        label = phone.label;
        CNPhoneNumber *phonNumber = (CNPhoneNumber *)phone.value;
        NSLog(@"label=%@, value=%@", label, phonNumber.stringValue);
        phoneStr = phonNumber.stringValue;
    }
    
    //剔除特殊符号
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@")" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
    NSString *name  = @"";
    if(![givenName isEqualToString:@""]){
        name = givenName;
    }else if(![familyName isEqualToString:@""]){
        name = familyName;
    }else{
        name = label;
    }
    
    self.callback(@{
        @"name":name ,
        @"phone": phoneStr,
    });
}


/*
 跳转到哦详情页面了
-(void)contactPicker:(CNContactPickerViewController*)picker didSelectContactProperty:(CNContactProperty*)contactProperty
{
    if (![contactProperty.value respondsToSelector:@selector(stringValue)]) {
        return;
    }
    //获取联系人信息
    NSString* firstName = contactProperty.contact.familyName;//姓
    NSString* lastName = contactProperty.contact.givenName;//名
    NSString* middleName = contactProperty.contact.middleName;//名
    //    NSString* phoneLabel = contactProperty.label;//号码类型
    
    NSString* phoneNum = [contactProperty.value stringValue];//号码
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@")" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSDictionary*dict = @{
        @"familyName":firstName,
        @"givenName":lastName,
        @"middleName":middleName,
        @"phoneNumbers":@[@{@"number":phoneNum}]
    };
    
    NSDictionary *dictr = [self contactsConversion:dict];
    NSLog(@"dictr----%@",dictr);
    

    self.callback(dictr);

    
}
 */
 
@end
